package com.apex.sdk.ui;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apex.bluetooth.callback.BatterInfoCallback;
import com.apex.bluetooth.callback.BleConnectStatusListener;
import com.apex.bluetooth.callback.CombinationCallback;
import com.apex.bluetooth.callback.DataReportCallback;
import com.apex.bluetooth.callback.DataResponseCallback;
import com.apex.bluetooth.callback.FeaturesCallback;
import com.apex.bluetooth.callback.GeneralCallback;
import com.apex.bluetooth.callback.InfoPushCallback;
import com.apex.bluetooth.callback.MacAddressCallback;
import com.apex.bluetooth.callback.MotionDataReportCallback;
import com.apex.bluetooth.callback.WatchInfoCallback;
import com.apex.bluetooth.core.EABleManager;
import com.apex.bluetooth.enumeration.CommonFlag;
import com.apex.bluetooth.enumeration.EABleConnectState;
import com.apex.bluetooth.enumeration.EABleSportStatus;
import com.apex.bluetooth.enumeration.MotionReportType;
import com.apex.bluetooth.enumeration.QueryWatchInfoType;
import com.apex.bluetooth.model.EABleBatInfo;
import com.apex.bluetooth.model.EABleBindInfo;
import com.apex.bluetooth.model.EABleBloodOxygen;
import com.apex.bluetooth.model.EABleCombination;
import com.apex.bluetooth.model.EABleDailyData;
import com.apex.bluetooth.model.EABleDev;
import com.apex.bluetooth.model.EABleExecutiveResponse;
import com.apex.bluetooth.model.EABleFeatures;
import com.apex.bluetooth.model.EABleGpsData;
import com.apex.bluetooth.model.EABleHabitRecord;
import com.apex.bluetooth.model.EABleHeartData;
import com.apex.bluetooth.model.EABleInfoPush;
import com.apex.bluetooth.model.EABleMotionHeart;
import com.apex.bluetooth.model.EABleMtu;
import com.apex.bluetooth.model.EABleMultiData;
import com.apex.bluetooth.model.EABleMusicControl;
import com.apex.bluetooth.model.EABleMusicRespond;
import com.apex.bluetooth.model.EABlePaceData;
import com.apex.bluetooth.model.EABlePhoneResponse;
import com.apex.bluetooth.model.EABlePressureData;
import com.apex.bluetooth.model.EABleQueryMusic;
import com.apex.bluetooth.model.EABleReportMonitorData;
import com.apex.bluetooth.model.EABleReportSportData;
import com.apex.bluetooth.model.EABleRestingRateData;
import com.apex.bluetooth.model.EABleSleepData;
import com.apex.bluetooth.model.EABleSleepScore;
import com.apex.bluetooth.model.EABleSocialResponse;
import com.apex.bluetooth.model.EABleStepFrequencyData;
import com.apex.bluetooth.model.EABleSwitch;
import com.apex.bluetooth.model.EABleTimelyData;
import com.apex.bluetooth.model.EABleWatchInfo;
import com.apex.bluetooth.utils.LogData2File;
import com.apex.bluetooth.utils.LogUtils;
import com.apex.lie_sheng_jie.watcha.JieliWatchFaceManager;
import com.apex.sdk.R;
import com.apex.sdk.databinding.ActivityHomeBinding;
import com.apex.sdk.dialog.WaitingDialog;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.IllegalFormatCodePointException;
import java.util.List;


public class HomeActivity extends AppCompatActivity {
    private String blueAddress;
    String[] apiList;
    private ItemAdapter itemAdapter;
    private final String TAG = this.getClass().getSimpleName();
    DeviceConnectListener deviceConnectListener;
    private int isConnected = -1;
    private WaitingDialog waitingDialog;
    private String btMac;
    private String watchName;
    volatile boolean autoReconnection;
    volatile boolean disconnectTest;
    volatile boolean resetWatch;
    long disconnectTime = -1;
    private int len = -1;
    volatile boolean isDestroy;
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (isDestroy) {
                return;
            }
            if (msg.what == 0x31) {

                activityHomeBinding.timeHint.setVisibility(View.GONE);
                activityHomeBinding.disconnectTime.setText("");
                activityHomeBinding.connectState.setText(getString(R.string.device_connected));
                //获取手表信息

            } else if (msg.what == 0x32) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.not_found), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x33) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.closed), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x34) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x35) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.unsupported), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x36) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.location_permission), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x37) {
                activityHomeBinding.connectState.setText(getString(R.string.connection_failed));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.connection_timed_out), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x38) {
                activityHomeBinding.connectState.setText(getString(R.string.disconnect));
                if (disconnectTime == -1) {
                    activityHomeBinding.timeHint.setVisibility(View.VISIBLE);
                    Date date = new Date();
                    disconnectTime = date.getTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
                    activityHomeBinding.disconnectTime.setText(simpleDateFormat.format(date));
                }
                Toast.makeText(HomeActivity.this, getString(R.string.disconnect), Toast.LENGTH_SHORT).show();
                if ((autoReconnection || resetWatch || disconnectTest) && !isDestroy) {
                    EABleManager.getInstance().disconnectPeripheral();
                    mHandler.removeCallbacksAndMessages(null);
                    mHandler.sendEmptyMessageDelayed(0x100, 5000);
                }
            } else if (msg.what == 0x45) {
                if (len == -1 || len == apiList.length) {
                    return;
                }
                itemAdapter.notifyItemRangeChanged(len, apiList.length);
            } else if (msg.what == 0x100) {
                Log.e(TAG, "开始连接蓝牙");
                isConnected = 0;
                try {
                    deviceConnectListener = new DeviceConnectListener();
                    EABleManager.getInstance().connectToPeripheral(blueAddress, HomeActivity.this, deviceConnectListener, 128, new DataReportListener(), new MotionListener());
                } catch (Exception e) {
                    isConnected = -1;
                    Log.e(TAG, "连接时出现异常:" + e.getMessage());
                }
            } else if (msg.what == 0x87) {
                if (isConnected == 1) {
                    if (resetWatch && !isDestroy) {
                        EABleDev eaBleDev = new EABleDev();
                        eaBleDev.setE_ops(EABleDev.DevOps.restore_factory);
                        EABleManager.getInstance().setDeviceOps(eaBleDev, new GeneralCallback() {
                            @Override
                            public void result(boolean b) {
                                if (!b) {
                                    if (mHandler != null && !isDestroy) {
                                        Log.e(TAG, "再次重置手表");
                                        mHandler.removeCallbacksAndMessages(null);
                                        mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                    }
                                }
                            }

                            @Override
                            public void mutualFail(int i) {
                                LogData2File.getInstance().saveLogData("重置手表时错误:" + i);
                                if (mHandler != null && !isDestroy) {
                                    mHandler.removeCallbacksAndMessages(null);
                                    mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                }
                            }
                        });
                    } else {
                        LogData2File.getInstance().saveLogData("主动关闭蓝牙连接");
                        EABleManager.getInstance().disconnectPeripheral();
                        activityHomeBinding.connectState.setText(getString(R.string.disconnect));
                        if (mHandler != null && !isDestroy) {
                            mHandler.removeCallbacksAndMessages(null);
                            mHandler.sendEmptyMessageDelayed(0x100, 5000);
                        }
                    }
                }
            }
        }
    };

    ActivityHomeBinding activityHomeBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityHomeBinding = ActivityHomeBinding.inflate(getLayoutInflater());
        setContentView(activityHomeBinding.getRoot());
        blueAddress = getIntent().getStringExtra("blue_address");
        boolean isChecked = getIntent().getBooleanExtra("checked", false);
        List<String> permission = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permission.add(Manifest.permission.READ_MEDIA_IMAGES);
            permission.add(Manifest.permission.READ_MEDIA_AUDIO);
            permission.add(Manifest.permission.READ_MEDIA_VIDEO);
        }
        permission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        permission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        ActivityCompat.requestPermissions(this, permission.toArray(new String[0]), 0x800);
        autoReconnection = isChecked;
        disconnectTest = isChecked;
        resetWatch = getIntent().getBooleanExtra("resetWatch", false);
        Log.e(TAG, "自动重连:" + autoReconnection + ",断连测试:" + disconnectTest + ",重置连接测试:" + resetWatch);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(HomeActivity.this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        activityHomeBinding.functionList.setLayoutManager(linearLayoutManager);
        apiList = getResources().getStringArray(R.array.api_list);
        len = apiList.length;
        itemAdapter = new ItemAdapter();
        activityHomeBinding.functionList.setAdapter(itemAdapter);
        activityHomeBinding.connectState.setText(getString(R.string.not_connected));
        LogData2File.getInstance().init(HomeActivity.this);
        LogData2File.getInstance().setSaveLog(true);
        LogData2File.getInstance().setSaveOriginalData(true);
        if (TextUtils.isEmpty(blueAddress)) {
            Toast.makeText(HomeActivity.this, getString(R.string.device_address), Toast.LENGTH_SHORT).show();
        } else {
            EABleConnectState connectState = EABleManager.getInstance().getDeviceConnectState();
            if (connectState == EABleConnectState.STATE_IDLE || connectState == EABleConnectState.STATE_DISCONNECT) {
                try {
                    activityHomeBinding.connectState.setText(getString(R.string.connecting));

                    EABleManager.getInstance().initDB(HomeActivity.this);

                    EABleManager.getInstance().saveMultiData(true);
                    /**
                     EABleManager.getInstance().saveStressData(true);
                     EABleManager.getInstance().saveHeartData(true);
                     EABleManager.getInstance().saveDailyData(true);
                     EABleManager.getInstance().saveBloodData(true);
                     EABleManager.getInstance().saveRestingHeartData(true);
                     EABleManager.getInstance().saveSleepData(true);
                     */
                    try {
                        isConnected = 0;
                        deviceConnectListener = new DeviceConnectListener();
                        EABleManager.getInstance().connectToPeripheral(blueAddress, HomeActivity.this, deviceConnectListener, 128, new DataReportListener(), new MotionListener());
                    } catch (Exception e) {
                        isConnected = 2;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                if (connectState == EABleConnectState.STATE_CONNECTED) {
                    activityHomeBinding.connectState.setText(getString(R.string.device_connected));
                    isConnected = 1;
                }
            }

        }


    }

    class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHold> {
        @NonNull
        @Override
        public ItemHold onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(HomeActivity.this).inflate(R.layout.adapter_home_recyclerview, parent, false);
            return new ItemHold(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull ItemHold holder, int position) {
            if (apiList == null) {
                return;
            }
            holder.apiName.setText(apiList[position]);
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (isDestroy) {
                        return;
                    }
                    String apiName = apiList[position];
                    if (getString(R.string.auto_reconnection).equalsIgnoreCase(apiName)) {
                        autoReconnection = true;
                        if (isConnected == 1 || isConnected == 0) {
                            return;
                        }
                        if (EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_IDLE || EABleManager.getInstance().getDeviceConnectState() == EABleConnectState.STATE_DISCONNECT) {
                            if (mHandler != null && !isDestroy) {
                                mHandler.removeCallbacksAndMessages(null);
                                mHandler.sendEmptyMessageDelayed(0x87, 5000);
                            }
                        }
                        return;
                    }
                    if (isConnected != 1) {
                        Toast.makeText(HomeActivity.this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (getString(R.string.watch_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, WatchInfoActivity.class));

                    } else if (getString(R.string.user_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, UserInfoActivity.class));
                    } else if (getString(R.string.sync_time).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SyncTimeActivity.class));
                    } else if (getString(R.string.binding).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, BindActivity.class));
                    } else if (getString(R.string.screen_brightness).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, ScreenBrightnessActivity.class));

                    } else if (getString(R.string.rest_screen_time).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, RestScreenActivity.class));

                    } else if (getString(R.string.power_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, PowerActivity.class));
                    } else if (getString(R.string.language_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, LanguageActivity.class));
                    } else if (getString(R.string.equipment_unit).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, DeviceUnitActivity.class));
                    } else if (getString(R.string.equipment_operation).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, DeviceActionActivity.class));
                    } else if (getString(R.string.do_not_disturb).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, NoDisturbActivity.class));
                    } else if (getString(R.string.sync_hometown_time).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SyncHomeTimeActivity.class));
                    } else if (getString(R.string.daily_objectives).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, DailyObjectivesActivity.class));
                    } else if (getString(R.string.sleep_monitoring).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SleepMonitoringActivity.class));
                    } else if (getString(R.string.heart_rate_monitoring).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, HeartReteActivity.class));
                    } else if (getString(R.string.sedentary_monitoring).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SedentaryActivity.class));
                    } else if (getString(R.string.reminder_operation).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, PushInfoActivity.class));
                    } else if (getString(R.string.weather_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, WeatherActivity.class));
                    } else if (getString(R.string.reminder_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, RemindActivity.class));
                    } else if (getString(R.string.alarm_clock).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, AlarmActivity.class));
                    } else if (getString(R.string.schedule).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, ScheduleActivity.class));
                    } else if (getString(R.string.distance_unit).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, DistanceUnitActivity.class));
                    } else if (getString(R.string.weight_unit).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, WeightUnitActivity.class));
                    } else if (getString(R.string.calorie_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, CalorieSwitchActivity.class));
                    } else if (getString(R.string.bright_screen_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, BrightScreenActivity.class));
                    } else if (getString(R.string.sync_motion_data).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SyncMonitorActivity.class));
                    } else if (getString(R.string.combination_information).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, CombinationActivity.class));
                    } else if (getString(R.string.main_menu).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, MenuActivity.class));
                    } else if (getString(R.string.physiological_period).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, PeriodActivity.class));
                    } else if (getString(R.string.dial_ID).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SystemDialActivity.class));
                    } else if (getString(R.string.push_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, PushSwitchActivity.class));
                    } else if (getString(R.string.blood_pressure_calibration).equalsIgnoreCase(apiName)) {

                    } else if (getString(R.string.automatic_monitoring_information).equalsIgnoreCase(apiName)) {

                    } else if (getString(R.string.commissioning_information).equalsIgnoreCase(apiName)) {

                    } else if (getString(R.string.Habit_set).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, HabitSettingActivity.class));
                    } else if (getString(R.string.ota).equalsIgnoreCase(apiName)) {
                        Intent intent = new Intent(HomeActivity.this, OtaActivity.class);
                        intent.putExtra("addressMac", blueAddress);
                        startActivity(intent);
                    } else if (getString(R.string.Today_sport_data).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, TodayTotalSportDataActivity.class));
                    } else if (getString(R.string.Add_contact).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, AddContactActivity.class));
                    } else if (getString(R.string.Add_reminder).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, MonitorReminderActivity.class));
                    } else if (getString(R.string.app_sport).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, AppSports.class));
                    } else if (getString(R.string.transfer_motion).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SetAppSportData.class));
                    } else if (getString(R.string.check).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, CheckActivity.class));
                    } else if (getString(R.string.sync_motion_data_by_type).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, GetMotionDataByTypeActivity.class));
                    } else if (getString(R.string.sleep_blood_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SleepBloodMonitorActivity.class));
                    } else if (getString(R.string.stress_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, StressMonitorActivity.class));
                    } else if (getString(R.string.time_data_report_switch).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, TimeDataSwitchActivity.class));
                    } else if (getString(R.string.vibration_mode).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, VibrateModeActivity.class));
                    } else if (getString(R.string.watch_sport).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, WatchSportActivity.class));
                    } else if (getString(R.string.sos).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, SosActivity.class));
                    } else if (getString(R.string.lock_screen).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, LockScreenActivity.class));
                    } else if (getString(R.string.location).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, TransLocation2Watch.class));
                    } else if ((getString(R.string.sport) + " (show sport id)").equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, ShowMultiSport.class));
                    } else if (getString(R.string.reminder_on_screen).equalsIgnoreCase(apiName)) {
                        startActivity(new Intent(HomeActivity.this, ReminderScreen.class));
                    } else {
                        Toast.makeText(HomeActivity.this, getString(R.string.unknown), Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

        @Override
        public int getItemCount() {
            return apiList == null ? 0 : apiList.length;
        }

        class ItemHold extends RecyclerView.ViewHolder {
            TextView apiName;

            public ItemHold(@NonNull View itemView) {
                super(itemView);
                apiName = itemView.findViewById(R.id.api_name);
            }
        }
    }

    @Override
    protected void onDestroy() {
        isDestroy = true;
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        if (waitingDialog != null) {
            waitingDialog.dismiss();
            waitingDialog = null;
        }
        EABleManager.getInstance().disconnectPeripheral();
        itemAdapter = null;
        apiList = null;
        super.onDestroy();
    }

    public class DeviceConnectListener implements BleConnectStatusListener {
        private final String TAG = this.getClass().getSimpleName();

        @Override
        public void deviceConnected() {
            Log.i(TAG, "收到设备连接回调");
            if (isDestroy) {
                return;
            }
            isConnected = 1;
            disconnectTime = -1;
            if (mHandler != null && !isDestroy) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x31);
            }
            if (isDestroy) {
                return;
            }
            // JieliWatchFaceManager.getInstance().addConnectListener();

            JieliWatchFaceManager.getInstance().release();
            JieliWatchFaceManager.getInstance().setBleConnectStatusListener(deviceConnectListener);
            JieliWatchFaceManager.getInstance().init();
            EABleManager.getInstance().queryWatchInfo(QueryWatchInfoType.watch_info, new WatchInfoCallback() {
                @Override
                public void watchInfo(EABleWatchInfo eaBleWatchInfo) {
                    if (isDestroy) {
                        return;
                    }
                    if (eaBleWatchInfo != null) {
                        Log.e(TAG, "手表信息:" + JSON.toJSONString(eaBleWatchInfo));
//判断是否支持功能列表
                        if (eaBleWatchInfo.getProj_settings() == 1) {
                            EABleManager.getInstance().queryWatchInfo(QueryWatchInfoType.features, new FeaturesCallback() {
                                @Override
                                public void featuresList(EABleFeatures eaBleFeatures) {
                                    if (isDestroy) {
                                        return;
                                    }
                                    if (eaBleFeatures != null) {
                                        Log.e(TAG, "功能列表:" + JSON.toJSONString(eaBleFeatures));
                                        if (eaBleFeatures.getContact_sos() == 1 && !isDestroy) {
                                            String[] itemList = new String[apiList.length + 1];
                                            System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                                            itemList[apiList.length] = getString(R.string.sos);
                                            apiList = itemList;


                                        }
                                        if (eaBleFeatures.getSupport_pwd() == 1 && !isDestroy) {
                                            String[] itemList = new String[apiList.length + 1];
                                            System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                                            itemList[apiList.length] = getString(R.string.lock_screen);
                                            apiList = itemList;
                                        }
                                        if (eaBleFeatures.getApp_gps_location_support() == 1 && !isDestroy) {
                                            String[] itemList = new String[apiList.length + 1];
                                            System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                                            itemList[apiList.length] = getString(R.string.location);
                                            apiList = itemList;
                                        }
                                        if (eaBleFeatures.getAncs_light_sw_support() == 1 && !isDestroy) {
                                            String[] itemList = new String[apiList.length + 1];
                                            System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                                            itemList[apiList.length] = getString(R.string.reminder_on_screen);
                                            apiList = itemList;
                                        }
                                        String[] itemList = new String[apiList.length + 1];
                                        System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                                        itemList[itemList.length - 1] = getString(R.string.sport) + " (show sport id)";
                                        apiList = itemList;
                                        if (mHandler != null && !isDestroy) {
                                            mHandler.sendEmptyMessage(0x45);
                                        }
                                        if (eaBleFeatures.getBt_one_key_connect() == 1) {
                                            if (eaBleFeatures.getSupport_get_bt_mac() == 1) {
                                                if (isDestroy) {
                                                    return;
                                                }
                                                EABleManager.getInstance().queryWatchInfo(QueryWatchInfoType.bt_mac, new MacAddressCallback() {
                                                    @Override
                                                    public void macAddress(String s) {
                                                        Log.e(TAG, "BT地址:" + s);

                                                        btMac = s;
                                                        if (disconnectTest || resetWatch) {
                                                            if (mHandler != null && !isDestroy) {
                                                                mHandler.removeCallbacksAndMessages(null);
                                                                mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                                            }
                                                        }
                                                    }

                                                    @Override
                                                    public void mutualFail(int i) {
                                                        Log.e(TAG, "获取BT地址失败:" + i);
                                                        if (disconnectTest || resetWatch) {
                                                            if (mHandler != null && !isDestroy) {
                                                                mHandler.removeCallbacksAndMessages(null);
                                                                mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                                            }
                                                        }
                                                    }
                                                });

                                            } else {
                                                btMac = blueAddress;
                                                if (disconnectTest || resetWatch) {
                                                    if (mHandler != null && !isDestroy) {
                                                        mHandler.removeCallbacksAndMessages(null);
                                                        mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                                    }
                                                }
                                            }
                                        }

                                    }
                                }

                                @Override
                                public void mutualFail(int i) {
                                    Log.e(TAG, "获取功能列表失败:" + i);
                                    if (disconnectTest || resetWatch) {
                                        if (mHandler != null && !isDestroy) {
                                            mHandler.removeCallbacksAndMessages(null);
                                            mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                        }
                                    }
                                }
                            });
                        } else {
                            String[] itemList = new String[apiList.length + 1];
                            System.arraycopy(apiList, 0, itemList, 0, apiList.length);
                            itemList[itemList.length - 1] = getString(R.string.sport) + " (show sport id)";
                            btMac = blueAddress;
                            if (disconnectTest || resetWatch) {
                                if (mHandler != null && !isDestroy) {
                                    mHandler.removeCallbacksAndMessages(null);
                                    mHandler.sendEmptyMessageDelayed(0x87, 5000);
                                }
                            }
                        }

                    }
                }

                @Override
                public void mutualFail(int i) {
                    Log.e(TAG, "查询手表信息失败:" + i);
                    if (disconnectTest || resetWatch) {
                        if (mHandler != null && !isDestroy) {
                            mHandler.removeCallbacksAndMessages(null);
                            mHandler.sendEmptyMessageDelayed(0x87, 5000);
                        }
                    }

                }
            });


        }

        @Override
        public void deviceDisconnect() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogUtils.e(TAG, "断开连接");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x38);

            }


        }

        @Override
        public void deviceNotFind() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("未找到相关设备回调");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x32);

            }


        }

        @Override
        public void unopenedBluetooth() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("蓝牙未打开");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x33);

            }


        }

        @Override
        public void connectError(int errorCode) {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("蓝牙连接出现错误");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x34);

            }

        }

        @Override
        public void unsupportedBLE() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("不支持BLE连接");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x35);

            }

        }

        @Override
        public void notOpenLocation() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("未开启定位权限");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x36);

            }

        }

        @Override
        public void connectTimeOut() {
            if (isDestroy) {
                return;
            }
            EABleManager.getInstance().disconnectPeripheral();
            isConnected = 2;
            LogData2File.getInstance().saveLogData("连接超时的回调");
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler.sendEmptyMessage(0x37);

            }

        }
    }

    public class DataReportListener implements DataReportCallback {

        @Override
        public void searchPhone() {//Watch search mobile phone,The app does not need to reply
            Log.e(TAG, "search phone");

        }

        @Override
        public void stopSearchPhone() {//Watch search mobile phone,The app does not need to reply
            Log.e(TAG, " stop search phone");
        }

        @Override
        public void connectCamera() {//Need reply
            Log.e(TAG, "connect camera");
            EABlePhoneResponse eaBlePhoneResponse = new EABlePhoneResponse();
            eaBlePhoneResponse.setEaBleExecutiveResponse(EABleExecutiveResponse.success);
            eaBlePhoneResponse.setId(2);
            EABleManager.getInstance().mobileOperationResponse(eaBlePhoneResponse, new DataResponseCallback() {
                @Override
                public void mutualSuccess() {

                }

                @Override
                public void mutualFail(int errorCode) {

                }
            });
        }

        @Override
        public void takePhoto() {//Need reply
            Log.e(TAG, "take photo");
            EABlePhoneResponse eaBlePhoneResponse = new EABlePhoneResponse();
            eaBlePhoneResponse.setEaBleExecutiveResponse(EABleExecutiveResponse.success);
            eaBlePhoneResponse.setId(3);
            EABleManager.getInstance().mobileOperationResponse(eaBlePhoneResponse, new DataResponseCallback() {
                @Override
                public void mutualSuccess() {

                }

                @Override
                public void mutualFail(int errorCode) {

                }
            });
        }

        @Override
        public void endTakePhoto() {//Need reply
            Log.e(TAG, "end take photo");
            EABlePhoneResponse eaBlePhoneResponse = new EABlePhoneResponse();
            eaBlePhoneResponse.setEaBleExecutiveResponse(EABleExecutiveResponse.success);
            eaBlePhoneResponse.setId(4);
            EABleManager.getInstance().mobileOperationResponse(eaBlePhoneResponse, new DataResponseCallback() {
                @Override
                public void mutualSuccess() {

                }

                @Override
                public void mutualFail(int errorCode) {

                }
            });
        }

        @Override
        public void updateWeather() {//Need reply,Then synchronize the weather data to the device
            Log.e(TAG, "update weather");
            //replay

            //Synchronize the weather. Please check the weather information for details

        }

        @Override
        public void circadian() {//Need reply,Then Synchronize physiological period data to the watch
            Log.e(TAG, "Physiological period");
        }

        @Override
        public void updateAgps() {//Need reply, Then Update AGPs
            //reply

            //Update AGPs. For details, please see AGPs update in Ota
        }

        @Override
        public void transmissionComplete() {//The app does not need to reply,After receiving the entry command,
            // it indicates that the interaction between the watch motion data and the app is completed. At this time, the app can process the motion data
            Log.e(TAG, "transmissionComplete");
            //  startActivity(new Intent(HomeActivity.this, DBActivity.class));

        }

        @Override
        public void stopSearchWatch() {
            Log.e(TAG, "停止查找手表");
        }

        @Override
        public void queryMusic(EABleQueryMusic eaBleQueryMusic) {
            Log.e(TAG, "query Music");
            EABleMusicRespond eaBleMusicRespond = new EABleMusicRespond();
            eaBleMusicRespond.setArtist("Singer");
            eaBleMusicRespond.setContent("Music name");
            eaBleMusicRespond.setDuration(250);
            eaBleMusicRespond.setVolume(30);
            eaBleMusicRespond.setE_status(EABleMusicRespond.MusicStatus.playing);
            eaBleMusicRespond.setElapsedtime(100);
            EABleManager.getInstance().musicQueryResponse(eaBleMusicRespond, new DataResponseCallback() {
                @Override
                public void mutualSuccess() {

                }

                @Override
                public void mutualFail(int errorCode) {

                }
            });
        }

        @Override
        public void musicControl(EABleMusicControl eaBleMusicControl) {
            Log.e(TAG, "music Control");
            //Watch control player
            EABleMusicControl.MusicControl musicControl = eaBleMusicControl.getE_ops();
            if (musicControl != null) {
                if (musicControl == EABleMusicControl.MusicControl.next_song) {
                    LogUtils.i(TAG, "Next song");
                } else if (musicControl == EABleMusicControl.MusicControl.previous_song) {
                    LogUtils.i(TAG, " Previous song");
                } else if (musicControl == EABleMusicControl.MusicControl.play_start) {
                    LogUtils.i(TAG, "Start playing");
                } else if (musicControl == EABleMusicControl.MusicControl.play_stop) {
                    LogUtils.i(TAG, "Stop playing");
                } else if (musicControl == EABleMusicControl.MusicControl.volume_up) {
                    LogUtils.i(TAG, "VOL UP");
                } else if (musicControl == EABleMusicControl.MusicControl.volume_reduction) {
                    LogUtils.i(TAG, "VOL DN");
                }
            }
            //reply
            EABleMusicRespond eaBleMusicRespond = new EABleMusicRespond();
            eaBleMusicRespond.setArtist("Singer");
            eaBleMusicRespond.setContent("Music name");
            eaBleMusicRespond.setDuration(250);
            eaBleMusicRespond.setVolume(30);
            eaBleMusicRespond.setE_status(EABleMusicRespond.MusicStatus.playing);
            eaBleMusicRespond.setElapsedtime(100);
            EABleManager.getInstance().musicQueryResponse(eaBleMusicRespond, new DataResponseCallback() {
                @Override
                public void mutualSuccess() {

                }

                @Override
                public void mutualFail(int errorCode) {

                }
            });
        }

        @Override
        public void socialResponse(EABleSocialResponse eaBleSocialResponse) {//The social Reply of the watch is a reserved item and is not used for the time being

        }

        @Override
        public void mtu(EABleMtu eaBleMtu) {

        }

        /**
         * Answer the phone   You need to implement it yourself
         */
        @Override
        public void answerIncoming() {
            Log.e(TAG, "接听.....");

        }

        /**
         * Hang up  You need to implement it yourself
         */
        @Override
        public void hangUpIncoming() {
            Log.e(TAG, "挂断.....");
        }


        @Override
        public void appSportStatus(EABleSportStatus sportStatus) {
            Log.e(TAG, "当前上报的App运动状态:" + sportStatus.toString());

        }

        @Override
        public void timelyData(EABleTimelyData eaBleTimelyData) {
            Log.e(TAG, "时时数据:" + eaBleTimelyData.toString());
            if (eaBleTimelyData != null) {
                if (LiveEventBus.get("timeData") != null) {
                    LiveEventBus.get("timeData").post(eaBleTimelyData.toString());
                }
            }


        }

        @Override
        public void appSportData(EABleReportSportData eaBleReportSportData) {
            Log.e(TAG, "app运动上报数据:" + eaBleReportSportData.toString());

        }

        @Override
        public void disturbStatus(EABleSwitch eaBleSwitch) {
            Log.e(TAG, "勿扰模式开关状态:" + eaBleSwitch.toString());

        }

        @Override
        public void brightScreenStatus(EABleSwitch eaBleSwitch) {
            Log.e(TAG, "抬手亮屏开关状态:" + eaBleSwitch.toString());
        }

        @Override
        public void reportMonitorData(EABleReportMonitorData eaBleReportMonitorData) {
            Log.e(TAG, "手表开启心率,血氧,压力,呼吸的结果上报");
        }

        @Override
        public void startConnectBt() {
            Log.e(TAG, "开始连接BT");
            if (TextUtils.isEmpty(btMac) || !BluetoothAdapter.checkBluetoothAddress(btMac)) {
                Log.e(TAG, "bk地址不存在或者地址不合法");
            } else {
                Intent intent = new Intent("east.apex.bt.connect");
                intent.putExtra("bt_address", btMac);
                intent.setPackage(getPackageName());
                sendBroadcast(intent);
            }

        }

        @Override
        public void mutualFail(int errorCode) {


        }
    }

    public class MotionListener implements MotionDataReportCallback {
        @Override
        public void dailyExerciseData(List<EABleDailyData> sportList, CommonFlag mCommon) {
            if (sportList != null && !sportList.isEmpty()) {

                Log.e(TAG, "日常:" + JSONObject.toJSONString(sportList));


            }

        }

        @Override
        public void sleepData(List<EABleSleepData> sleepList, CommonFlag mCommon) {
            if (sleepList != null && !sleepList.isEmpty()) {
                Log.e(TAG, "睡眠:" + JSONObject.toJSONString(sleepList));


            }

        }

        @Override
        public void heartData(List<EABleHeartData> heartList, CommonFlag mCommon) {
            if (heartList != null && !heartList.isEmpty()) {

                Log.e(TAG, "心率:" + JSONObject.toJSONString(heartList));


            }
        }

        @Override
        public void gpsData(List<EABleGpsData> gpsList, CommonFlag mCommon) {
            if (gpsList != null && !gpsList.isEmpty()) {

                Log.e(TAG, "GPS:" + JSONObject.toJSONString(gpsList));


            }
        }

        @Override
        public void multiMotionData(List<EABleMultiData> multiList, CommonFlag mCommon) {
            if (multiList != null && !multiList.isEmpty()) {
                Log.e(TAG, "运动:" + JSONObject.toJSONString(multiList));

            }

        }

        @Override
        public void bloodOxygenData(List<EABleBloodOxygen> oxygenList, CommonFlag mCommon) {
            if (oxygenList != null && !oxygenList.isEmpty()) {

                Log.e(TAG, "血氧:" + JSONObject.toJSONString(oxygenList));


            }
        }

        @Override
        public void pressureData(List<EABlePressureData> pressureList, CommonFlag mCommon) {
            if (pressureList != null && !pressureList.isEmpty()) {

                Log.e(TAG, "压力:" + JSONObject.toJSONString(pressureList));


            }
        }

        @Override
        public void stepFrequencyData(List<EABleStepFrequencyData> stepFreqList, CommonFlag mCommon) {
            if (stepFreqList != null && !stepFreqList.isEmpty()) {

                Log.e(TAG, "步频:" + JSONObject.toJSONString(stepFreqList));


            }

        }

        @Override
        public void speedData(List<EABlePaceData> paceList, CommonFlag mCommon) {
            if (paceList != null && !paceList.isEmpty()) {
                Log.e(TAG, "配速:" + JSONObject.toJSONString(paceList));
            }

        }


        @Override
        public void restingHeartRateData(List<EABleRestingRateData> restingList, CommonFlag mCommon) {
            if (restingList != null && !restingList.isEmpty()) {
                Log.e(TAG, "静息心率:" + JSONObject.toJSONString(restingList));


            }
        }

        @Override
        public void getHabitData(List<EABleHabitRecord> habitList, CommonFlag commonFlag) {
            if (habitList != null && !habitList.isEmpty()) {
                for (int i = 0; i < habitList.size(); i++) {
                    Log.e(TAG, "习惯记录:" + habitList.get(i).toString());
                }
            }
        }

        @Override
        public void getSleepScore(List<EABleSleepScore> list, CommonFlag commonFlag) {

        }

        @Override
        public void getMotionHr(List<EABleMotionHeart> list, CommonFlag commonFlag) {

        }

        @Override
        public void mutualFail(int errorCode) {

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0x800) {
            for (String permission : permissions) {
                Log.i(TAG, "当前权限：" + permission + ",授权结果：" + (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED ? "true" : "false"));
            }

        }
    }
}
